import { boot } from "quasar/wrappers";
import axios from "axios";
import { useUserStore } from "src/stores/modules/userStore";
import { useRouter } from "vue-router";
import UnauthorizedDialog from 'src/components/UnauthorizedDialog.vue'

import { Dialog } from 'quasar';

const router = useRouter()

const API_PREFIX = "/frontend";
const API_TSL_FRONTEND = "/api/frontend";

export function resolveDjangoUrl() {
  // console.log(process.env.DJANGO_URL)
  // if (process.env.DJANGO_URL && process.env.DJANGO_URL != '') {
  //   return process.env.DJANGO_URL;
  // }
  // return `${window.location.protocol}//${window.location.hostname}:8000`;
  // return 'https://ewouat.tslj.com.cn:8000';
  // return 'http://192.168.1.100:8000';
  return 'http://192.168.1.130:8000';

}


// const api = axios.create({ baseURL: resolveDjangoUrl() })
// const api = axios.create({ baseURL: 'https://test.admin.tsl-ewo.gnshk.com' })
// const api = axios.create({ baseURL: 'https://ewouat.tslj.com.cn:8000', timeout:300000 })
// const api = axios.create({ baseURL: 'http://192.168.1.100:8000', timeout:300000 })
const api = axios.create({ baseURL: 'http://192.168.1.130:8000', timeout:300000 })
// api.defaults.timeout = 1800000

export default boot(({ app }) => {
  const useUser = useUserStore();
  api.interceptors.request.use(
    function (config) {
      if (useUser.loginStatus) {
        config.headers.Authorization = `Bearer ${useUser.access_token}`;
      }
      return config;
    },
    function (error) {
      console.log(error);
      return Promise.reject(error);
    }
  );


  api.interceptors.response.use(
    (response) => {
      return response;
    },
    (error) => {
      if (error.response.status === 401) {
        console.log('hello?', error.response);
        Dialog.create({
          component:UnauthorizedDialog,
          componentProps: {
            text: error.response.data.detail,
            // ...more..props...
          },
          // class:'notice-dialog',
          // maximized: true,
          title: 'Unauthorized',
          message: '重新登入',
          persistent: true,
        }).onOk(async () => {
          window.location.href = '/auth'
        });
      }
        return Promise.reject(error);
        // other status error
       
    }
  );

  app.config.globalProperties.$axios = axios;
  app.config.globalProperties.$api = api;
});


export { api, API_PREFIX, API_TSL_FRONTEND };
